package cn.fanqinghong.basic.interceptor;

import cn.fanqinghong.basic.anno.PreAuthorize;
import cn.fanqinghong.basic.jwt.JwtUtils;
import cn.fanqinghong.basic.jwt.LoginResult;
import cn.fanqinghong.basic.jwt.Payload;
import cn.fanqinghong.basic.jwt.RsaUtils;
import cn.fanqinghong.basic.util.JwtRasHolder;
import cn.fanqinghong.system.mapper.PermissionMapper;
import cn.fanqinghong.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * FAN
 * 2022/6/18  16:46
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ///1.获取前端axios拦截器传过来的token
        String token = request.getHeader("token");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        //解密前端传过来的
        //2.判断token是否有值
        if (StringUtils.hasLength(token)){//2.1如果token有值
            /*//查询token的值
            Object loginTmp = redisTemplate.opsForValue().get(token);*/ //以前的方法从redis中获取
            //PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());//获得公钥
            //使用公钥对字符串进行解密
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();
            //判断loginTmp是否有值
            if (loginResult != null){
                //增加权限校验====即 登录之后，也需要查看是否有权限访问某个资源
                //1.区分是否是员工，是就需要校验权限
                Logininfo logininfo = loginResult.getLogininfo();
                //1.区分是否是员工，是就需要校验权限
                if (logininfo.getType() == 0){
                    //。得到当前请求的资源 url
                    HandlerMethod method = (HandlerMethod)handler;
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);

                    if (annotation != null){
                        //获得本次的sn
                        String currentSn = annotation.value();
                        //。查询出当前登录人拥有的权限的资源
                        List<String> permissions = permissionMapper.loadPermissionByLogininfoId(logininfo.getId());
                        //。判断permissions是否包含url
                        if (!permissions.contains(currentSn)){
                            //。 不包含。。提示权限不足，请联系管理员
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");//输出
                            writer.flush();//刷新
                            writer.close();//关闭流
                            return false;//阻止放行
                        }
                    }
                }

                /*//如果有值，先刷新过期时间
                redisTemplate.opsForValue().set(
                        token,
                        loginResult,
                        30,
                        TimeUnit.MINUTES
                );*/
                //放行
                return true;
            }
        }
        //2.2如果token没有值，拦截，回到登陆页面

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");//输出
        writer.flush();//刷新
        writer.close();//关闭流
        return false;//阻止放行
    }
}
